<template>
	<private_dialog ref="dialogRef" width="600" :beforeClose="dialogCancel">
		<el-form ref="formRef" :rules="fromRule" :model="form" inline label-width="auto">
			<el-row :gutter="20"> </el-row>
		</el-form>
	</private_dialog>
</template>

<script setup>
import { ref } from "vue";
import private_dialog from "@/components/confirmDialog/index.vue";
import { addDepartmentApi, editDepartmentApi } from "@/api/system/department";

const props = defineProps({
	fullData: { type: Array, required: true },
});
const emit = defineEmits(["updateFullData"]);

// DialogRef
const dialogRef = ref();
// Dialog关闭时
const dialogCancel = () => {
	formRef.value.resetFields();
	formRef.value.clearValidate();

	form.value = { name: "", key: "", status: "enable", pid: "", sort: 1 };
};
// 当前打开的Dialog类型
const currentDialogType = ref("add");

// 表单Ref
const formRef = ref();
// 表单数据
const form = ref({ name: "", key: "", status: "enable", pid: "", sort: 1 });
// 表单校验规则
const fromRule = {};

defineExpose({
	open: ({ type = "add", data } = {}) => {
		// 设置当前打开的Dialog类型
		currentDialogType.value = type;

		// 打开Dialog, 并设置回调.
		dialogRef.value.open({
			title: "操作",
			isAsync: true,
			// 打开后的回调.
			openAfter: () => {
				// 打开dialog后设置回显表单数据, 否则关闭后值不会清空.
				if (type === "edit") form.value = JSON.parse(JSON.stringify(data));
			},
			// 确认回调.
			confirm: async ({ stopLoading, done }) => {
				// 校验表单
				try {
					await formRef.value.validate();
				} catch (e) {
					return stopLoading();
				}

				try {
					// 添加部门
					if (type === "add") {
						await addDepartmentApi(form.value);
					}

					// 编辑部门
					if (type === "edit") {
						await editDepartmentApi(form.value);
					}

					done();
				} catch (e) {
					return stopLoading();
				}

				emit("updateFullData");
			},
			cancel: () => {},
		});
	},
});
</script>

<style scoped lang="scss"></style>
